<?php

namespace app\api\controller;

use app\common\controller\Api;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];





    public function test(){
        $url = config('site.syncurl').'/api/sync/testapi';
        $json = curl_post($url,[
            'goods_id'=>998,
            'appkey'=>config('site.appkey'),
        ]);
//
//        dump($json);
//        dump(json_decode($json,true));
    }


    public function tttt3(){
        $list = Db::name('analysis')->select();
        foreach ($list as $v){
            if($v['controller'] == 'sales/checkout'){
                $table = 'sales_checkout';
            }
            if($v['controller'] == 'sales/change'){
                $table = 'sales_change';
            }
            if($v['controller'] == 'purchase/diff'){
                $table = 'purchase_diff';
            }
            if($v['controller'] == 'purchase/enter'){
                $table = 'purchase_enter';
            }
            if($v['controller'] == 'stock/loss'){
                $table = 'stock_loss';
            }
            if($v['controller'] == 'sales/retreat'){
                $table = 'sales_retreat';
            }
            $row = Db::name($table)->where(array('id'=>$v['source_id']))->find();
            if($row){
               Db::name('analysis')->where(array('id'=>$v['id']))->update(array('explain'=>$row['explain']));
            }

        }
    }
    public function tttt2(){
        $list = Db::name('sales_slip')->select();
        foreach ($list as $v){
            $num = 0;
            $rows = Db::name('sales_goods')->where(array('sales_slip_id'=>$v['id']))->select();
            foreach ($rows as $val){
                $num+=$val['goods_num'];
            }
            Db::name('sales_slip')->where(array('id'=>$v['id']))->update(array('sales_num'=>$num));
        }
    }
    public function tttt1(){
        $rows =  Db::name('sales_checkout_goods')->select();
        foreach ($rows as $v){
            $tax = $v['tax']/100+1;
            $ht_price = $v['sale_price']*$tax;
            Db::name('sales_checkout_goods')->where(array('id'=>$v['id']))->update(array(
                'ht_price'=>$ht_price
            ));
        }
    }

    public function tttt(){
        $list =  Db::name('sales_checkout')->select();
//        dump($list);
        foreach ($list as $v){
            $rows =  Db::name('sales_checkout_goods')->where(array('sales_checkout_id'=>$v['id']))->select();
            $checkout_num = 0;
            foreach ($rows as $val){
                $data = array(
                    'admin_id'=>$v['admin_id'],
                    'group_id'=>$v['group_id'],
                    'company'=>$v['company'],
                    'operator'=>$v['operator'],
                    'createtime'=>$v['createtime'],
                );
                Db::name('sales_checkout_goods')->where(array('id'=>$val['id']))->update($data);
                $checkout_num += $val['goods_num'];
            }
            Db::name('sales_checkout')->where(array('id'=>$v['id']))->update(array('checkout_num'=>$checkout_num));
        }
    }
    /**
     * 首页
     *
     */
    public function getnumberss($cate_id,$numer = ''){
        $row = Db::name('goods_cate')->where(array('id'=>$cate_id))->find();
        if($row['pid']){
            $tnum = Db::name('goods_cate')->where(array('pid'=>$row['pid'],'id'=>array('<',$row['id'])))->count();
            $numer.=getnumbers($tnum);
            return $this->getnumberss($row['pid'],$numer);
        }
        $tnum = Db::name('goods_cate')->where(array('pid'=>0,'id'=>array('<',$row['id'])))->count();
        $numer.=getnumbers($tnum);
        return $numer;
    }
    public function index123123123(){
        $list = Db::name('customer_sales_log')->select();
        foreach ($list as $v){
            if($v['type_id'] == 1){
                $glist = Db::name('sales_slip')->where(array('id'=>$v['source_id']))->find();
            }else{
                $glist = Db::name('factory_sales')->where(array('id'=>$v['source_id']))->find();
            }
            Db::name('customer_sales_log')->where(array('id'=>$v['id']))->update(array('storehouse_id'=>$glist['storehouse_id']));
        }
    }
    public function index(){
        $list = Db::name('goods')->select();
        $num = 0;
        foreach ($list as $v){
            $row = Db::name('goods')->where(array('title'=>$v['title'],'specs'=>$v['specs']))->count();
            if($row >1){
                $num++;
            }
        }
        echo $num;
    }
    public function index1231231234(){
        $list = Db::name('customer_sales_log')->select();
        foreach ($list as $v){
            $glist = Db::name('goods_sales_log')->where(array('type_id'=>$v['type_id'],'source_id'=>$v['source_id']))->select();

            foreach ($glist as $value){
                Db::name('goods_sales_log')->where(array('id'=>$value['id']))->update(array(
                    'createtime'=>$v['createtime'],
                    'storehouse_id'=>$v['storehouse_id'],
                    'number'=>$v['number'],
                    'operator'=>$v['operator'],
                    'company'=>$v['company'],
                    'admin_id'=>$v['admin_id'],
                    'group_id'=>$v['group_id'],
                    'sales_log_id'=>$v['id'],
                ));
            }
        }
    }
    public function index11111(){
        $list = Db::name('sales_goods')->select();
        $lists = Db::name('factory_sales_goods')->select();
//        dump($list);
        foreach ($list as $v){
            $row = Db::name('sales_slip')->where(array('id'=>$v['sales_slip_id']))->find();
            $data[]= array(
              'goods_id'=>$v['goods_id'],
              'type'=>'销售单',
              'type_id'=>1,
              'number'=>$row['number'],
              'source_id'=>$row['id'],
              'createtime'=>$v['createtime'],
                'admin_id'=>$v['admin_id'],
                'group_id'=>$v['group_id'],
                'operator'=>$v['operator'],
                'company'=>$v['company'],
            );
        }
        foreach ($lists as $v){
            $row = Db::name('factory_sales')->where(array('id'=>$v['factory_sales_id']))->find();
            $data[]= array(
                'goods_id'=>$v['goods_id'],
                'type'=>'厂家直发',
                'type_id'=>2,
                'number'=>$row['number'],
                'source_id'=>$row['id'],
                'createtime'=>$v['createtime'],
                'admin_id'=>$v['admin_id'],
                'group_id'=>$v['group_id'],
                'operator'=>$v['operator'],
                'company'=>$v['company'],
            );
        }
//        dump($data);
        Db::name('goods_sales_log')->insertAll($data);
    }
    public function index213(){
        $list = Db::name('sales_slip')->select();
        $lists = Db::name('factory_sales')->select();

        foreach ($list as $v){
            $data[] = array(
                'customer_id'=>$v['customer_id'],
                'type'=>'销售单',
                'type_id'=>1,
                'number'=>$v['number'],
                'source_id'=>$v['id'],
                'createtime'=>$v['createtime'],
                'operator'=>$v['operator'],
                'company'=>$v['company'],
                'admin_id'=>$v['admin_id'],
                'group_id'=>$v['group_id'],
                'sales_num'=>$v['sales_num'],
                'actual_cost'=>$v['actual_cost'],
            );
        }
        foreach ($lists as $v){
            $data[] = array(
                'customer_id'=>$v['customer_id'],
                'type'=>'厂家直发单',
                'type_id'=>2,
                'number'=>$v['number'],
                'source_id'=>$v['id'],
                'createtime'=>$v['createtime'],
                'operator'=>$v['operator'],
                'company'=>$v['company'],
                'admin_id'=>$v['admin_id'],
                'group_id'=>$v['group_id'],
                'sales_num'=>$v['sales_num'],
                'actual_cost'=>$v['actual_cost'],
            );
        }
//       Db::name('customer_sales_log')->insertAll($data);
//        echo 2;
//      $list =  Db::name('customer')
//            ->alias('c')
//            ->join('sales_slip s','c.id = s.customer_id')
//            ->join('factory_sales f','c.id = s.customer_id')
//            ->where(array('c.id'=>3104))
//            ->select();




//        $is_sync = config('site.is_sync');
//        dump($is_sync);
//        $list = Db::name('goods')->where(array('cate_id'=>array('>',0),'number'=>0))->select();
//        foreach ($list as $v){
//            $number =$this->getnumberss($v['cate_id'],'');
//            if(strlen($number) == 6){
//                $tnum = Db::name('goods')->where(array('cate_id'=>$v['cate_id'],'id'=>array('<',$v['id'])))->count();
//                $number.=getnumber($tnum);
//                Db::name('goods')->where(array('id'=>$v['id']))->update(array('number'=>$number));
//            }
//        }
//        dump($list);
//        exit;
//        $res =  Db::name('analysis')->whereExp('group_id','> admin_id')->where(array('group_id'=>array('>','admin_id')))->select();
//        dump($res);
//
//        dump( Db::getLastSql());
//        $res =  Db::name('analysis')->where(array('group_id'=>array('exp','>admin_id')))->select();
//        dump($res);
//        dump( Db::getLastSql());
        //        $json = file_get_contents('http://zax.gotobby.xyz/Api/Goods/goodslist');
//        $json = json_decode($json,true);
//        foreach ($json['data'] as $v) {
//            dump($v);
//            $data = array(
//                'title'=>$v['goods_name'],
//                'cate_id'=>$v['cat_id'],
//                'place_origin'=>$v['goods_name'],
//                'unit'=>$v['goods_name'],
//                'createtime'=>$v['goods_name'],
//                'supplier_id'=>$v['goods_name'],
//                'specs'=>$v['goods_name'],
//                'brands_id'=>$v['goods_name'],
//            );
//            exit;
//        }
    }
    public function index1()
    {
        $json = file_get_contents('http://zax.gotobby.xyz/Api/Goods/catlist');
        $json = json_decode($json,true);
        foreach ($json['data'] as $v){
            $data[] = array(
                'id'=>$v['id'],
                'name'=>$v['cat_name'],
                'createtime'=>time(),
            );
            $json1 = file_get_contents('http://zax.gotobby.xyz/Api/Goods/catlistsmall?id='.$v['id']);
            $json1 = json_decode($json1,true);
            foreach ($json1['data']['catlist'] as $val){
                    $data[] = array(
                      'id'=>$val['id'],
                      'pid'=>$v['id'],
                      'name'=>$v['cat_name'],
                      'createtime'=>time(),
                    );
                    foreach ($val['cattwo'] as $va){
                        $data[] = array(
                            'id'=>$va['id'],
                            'pid'=>$val['id'],
                            'name'=>$va['cat_name'],
                            'createtime'=>time(),
                        );
                    }
            }

        }
      foreach ($data as $v){
          dump($v);
          Db::name('goods_cate')->insert($v);
      }

        $this->success('请求成功');
    }
    public function getcate(){
        $list = Db::table('dy_brand')->select();

//        dump($list);
        foreach ($list as $v){
            $data = array(
                'id'=>$v['id'],
                'name'=>$v['name'],
                'weigh'=>$v['sort'],
            );
        }

        exit;
    }
    public function handlebrand(){
        $list = Db::table('dy_brand')->select();
        foreach ($list as $v){
            $row = Db::name('supplier_brands')->where(array('name'=>$v['name']))->find();
            if(empty($row)){
                dump($v['name']);
            }
        }
    }
  public function handlegoods(){

//        $list =Db::table('dy_spec_goods_price')
//            ->alias('s')
//            ->join('dy_goods g','s.goods_id = g.goods_id')
//            ->limit(0,1)
//            ->select();
        $list = Db::table('dy_goods')
            ->alias('d')
            ->field('goods_name,goods_id,goods_type,cat_id,name')
            ->join('zax_supplier_brands b','d.brand_id = b.id','LEFT')
//            ->limit(0,10)
            ->select();
        $cates = Db::name('goods_cate')->select();

      foreach ($list as $k => $v){
             $list[$k]['cate_name'] = $this->handlecate($cates,$v['cat_id']);
             $specs =$this->ajaxGetSpecSelect($v['goods_id'],$v['goods_type']);
             if(!empty($specs)){
                $list[$k]['spec'] = $specs;
             }else{
                 $list[$k]['spec'] = [];
             }

        }

      $spreadsheet = new Spreadsheet();
      $worksheet = $spreadsheet->getActiveSheet();
      //设置工作表标题名称
        $worksheet->setTitle('11');
      //设置单元格内容
        $worksheet->setCellValueByColumnAndRow(1, 1, '商品名称');
        $worksheet->setCellValueByColumnAndRow(2, 1, '品牌');
        $worksheet->setCellValueByColumnAndRow(3, 1, '分类');
        $worksheet->setCellValueByColumnAndRow(4, 1, '规格');
      //合并单元格
//        $worksheet->mergeCells('A1:E1');
      $rows = $list;
      $len = count($rows);
      $j = 2;
      for ($i=0; $i < $len; $i++) {
          //从表格第3行开始
          $worksheet->setCellValueByColumnAndRow(1, $j, $rows[$i]['goods_name']);
          $worksheet->setCellValueByColumnAndRow(2, $j, $rows[$i]['name']);
          $worksheet->setCellValueByColumnAndRow(3, $j, $rows[$i]['cate_name']);
          if(!empty($rows[$i]['spec'])){
            foreach ($rows[$i]['spec'] as $v){
                $worksheet->setCellValueByColumnAndRow(4, $j, $v['item']);
                $j++;
            }
          }else{
              $worksheet->setCellValueByColumnAndRow(4, $j, '');
              $j++;
          }
      }

      $filename = '商品.xlsx';
      header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      header('Content-Disposition: attachment;filename="'.$filename.'"');
      header('Cache-Control: max-age=0');
      $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
      $writer->save('php://output');






    }
    public function handlecate($cates,$cate_id,$name = null){
        $pid = 0;
        foreach ($cates as $v){
            if($v['id'] == $cate_id){
                $name.='/'.$v['name'];
                $pid = $v['pid'];
            }
        }
        if($pid){
            return $this->handlecate($cates,$pid,$name);
        }
        return  $name;
    }
    public function ajaxGetSpecSelect($goods_id,$type_id){
        $specList = Db::table('dy_spec')->where("type_id", $type_id)->select();
        foreach ($specList as $k => $v)
            $specList[$k]['spec_item'] = Db::table('dy_spec_item')->where(['spec_id'=>$v['id']])->order('order_index')->select(); // 获取规格项
        $items_id = Db::table('dy_spec_goods_price')->where('goods_id', $goods_id)->field("key")->select();
//        dump($items_id);
        if(!isset($specList[0])){
            return [];
        }
        $ids = [];
        if(empty($items_id)){
//            echo 2;
            return [];
        }else{
            foreach ($items_id as $v){
                $ids[] = $v['key'];
            }
        }
        $specs = [];
        foreach ($specList[0]['spec_item'] as $v){
            if(in_array($v['id'],$ids)){
                $specs[] = $v;
            }
        }
        return $specs;
    }
}
